# 多个区域循环对比
# author:zhangzhuo
# date:20240524

import pygame
import configparser
import re
import shutil
import time
from PIL import Image, ImageGrab, ImageChops

pygame.mixer.init()
conf = configparser.ConfigParser()
conf.read('config.ini', encoding='utf-8')
rectnum = int(conf.get('rects', 'rectnum'))
rect_1 = conf.get('rects', 'rect_1')
rect_2 = conf.get('rects', 'rect_2')
rect_3 = conf.get('rects', 'rect_3')
rect_4 = conf.get('rects', 'rect_4')
rect_5 = conf.get('rects', 'rect_5')
rect_6 = conf.get('rects', 'rect_6')
rect_7 = conf.get('rects', 'rect_7')
rect_8 = conf.get('rects', 'rect_8')
rect_9 = conf.get('rects', 'rect_9')
rect_10 = conf.get('rects', 'rect_10')
sleeptime = conf.get('control', 'sleeptime')

# 无限循环对比
while 1:
    t = time.localtime()
    if (t.tm_hour == 0 and t.tm_min < 2):
        # 如果为新的一天则暂停1200秒等待页面数据刷新后重置各区域对比基准
        time.sleep(1200)
        for i in range(1, rectnum + 1):
            shutil.copy("cropimages\\"+str(i) + "_init.png", "cropimages\\"+str(i) + "_base.png")

    # 截取整个屏幕待用
    imgroot = ImageGrab.grab()
    imgroot.save("cropimages\\root.png")
    # 截取各个rect区域并对比
    for i in range(1, rectnum + 1):
        # 截取各个区域
        print("rect", i, "----", locals()['rect_' + str(i)])
        rect = locals()['rect_' + str(i)]
        xys = re.split(r'[^0-9]+', rect)
        xy = list(map(int, xys))
        imgi = imgroot.crop((xy[2], xy[3], xy[2] + xy[0], xy[3] + xy[1]))
        imgi.save("cropimages\\"+str(i) + ".png")
        imgib = Image.open("cropimages\\"+str(i) + "_base.png")
        # 对比区域图像
        imgdiff = ImageChops.difference(imgi, imgib)
        if imgdiff.getbbox():
            imgdiff.save("cropimages\\diff.png")
            mp3name=str("sounds\\")+str(i) + ".mp3"
            track = pygame.mixer.music.load(mp3name)
            pygame.mixer.music.play()
            while pygame.mixer.music.get_busy():
                time.sleep(5)
            with open("status\\"+str(i) + "_status.txt", 'w') as f:
                f.write('1')
            with open("log.txt", 'a') as f:
                f.write("rect changed! ---- :")
                f.write(str(i))
                f.write("  " + rect+"\r\n")
            # 页面锚定失败则不再做其他对比
            if (1 == i):
                break
    time.sleep(int(sleeptime))
